from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from django.core.paginator import Paginator
from .models import Question, TestSession, Answer
from .serializers import QuestionSerializer
import logging

logger = logging.getLogger(__name__)
import os

# 最大题目数量，默认为20
MAX_QUESTIONS = 20

# mbti_app/views.py
@api_view(['GET'])
def get_questions(request, page):
    """获取指定页面的题目"""
    try:
        # 可配置的每页题目数量，默认为5
        per_page = int(request.GET.get('per_page', 5))
        page = int(page)

        # 获取所有题目并按order排序，但只取前20道
        all_questions = Question.objects.all().order_by('order')[:MAX_QUESTIONS]
        total_questions = min(Question.objects.count(), MAX_QUESTIONS)

        # 使用分页器
        paginator = Paginator(all_questions, per_page)

        # 检查页码是否有效
        if page < 1 or page > paginator.num_pages:
            return Response(
                {'error': f'无效的页码: {page}. 有效范围: 1-{paginator.num_pages}'},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 获取当前页的题目
        questions_page = paginator.page(page)
        questions = list(questions_page.object_list)  # 转换为列表

        # 获取会话密钥
        session_key = request.GET.get('session_key')
        if not session_key:
            return Response(
                {'error': '需要会话密钥'},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 获取或创建会话
        session, created = TestSession.objects.get_or_create(session_key=session_key)

        # 获取已回答的题目ID
        answered_questions = Answer.objects.filter(session=session)
        answered_ids = {ans.question_id for ans in answered_questions}

        # 构建题目数据
        questions_data = []
        for question in questions:
            # 查找该题目的答案
            answer_obj = answered_questions.filter(question=question).first()
            answered = answer_obj is not None

            questions_data.append({
                'id': question.id,
                'text': question.text,
                'order': question.order,
                'answered': answered,
                'answerValue': answer_obj.value if answer_obj else None
            })

        return Response({
            'questions': questions_data,
            'current_page': page,
            'total_pages': paginator.num_pages,
            'total_questions': total_questions,
            'per_page': per_page,
            'max_questions': MAX_QUESTIONS  # 返回最大题目数供前端参考
        })

    except Exception as e:
        logger.error(f"获取题目时出错: {str(e)}")
        return Response(
            {'error': '服务器内部错误'},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )

#
# @api_view(['GET'])
# def get_questions(request, page):
#     """获取指定页面的题目"""
#     try:
#         per_page = 5
#         page = int(page)
#
#         # 获取所有题目并按order排序
#         all_questions = Question.objects.all().order_by('order')
#
#         # 使用分页器
#         paginator = Paginator(all_questions, per_page)
#
#         # 检查页码是否有效
#         if page < 1 or page > paginator.num_pages:
#             return Response(
#                 {'error': f'无效的页码: {page}. 有效范围: 1-{paginator.num_pages}'},
#                 status=status.HTTP_400_BAD_REQUEST
#             )
#
#         # 获取当前页的题目
#         questions_page = paginator.page(page)
#         questions = questions_page.object_list
#
#         # 获取会话密钥
#         session_key = request.GET.get('session_key')
#         if not session_key:
#             return Response(
#                 {'error': '需要会话密钥'},
#                 status=status.HTTP_400_BAD_REQUEST
#             )
#
#         # 获取或创建会话
#         session, created = TestSession.objects.get_or_create(session_key=session_key)
#
#         # 获取已回答的题目ID
#         answered_questions = Answer.objects.filter(session=session)
#         answered_ids = {ans.question_id for ans in answered_questions}
#
#         # 构建题目数据
#         questions_data = []
#         for question in questions:
#             # 查找该题目的答案
#             answer_obj = answered_questions.filter(question=question).first()
#             answered = answer_obj is not None
#
#             questions_data.append({
#                 'id': question.id,
#                 'text': question.text,
#                 'order': question.order,
#                 'answered': answered,
#                 'answerValue': answer_obj.value if answer_obj else None
#             })
#
#         return Response({
#             'questions': questions_data,
#             'current_page': page,
#             'total_pages': paginator.num_pages,
#             'total_questions': paginator.count
#         })
#
#     except Exception as e:
#         logger.error(f"获取题目时出错: {str(e)}")
#         return Response(
#             {'error': '服务器内部错误'},
#             status=status.HTTP_500_INTERNAL_SERVER_ERROR
#         )

@api_view(['POST'])
def submit_answers(request):
    """提交答案"""
    try:
        session_key = request.data.get('session_key')
        answers = request.data.get('answers', {})

        if not session_key:
            return Response(
                {'error': '需要会话密钥'},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 获取或创建会话
        session, created = TestSession.objects.get_or_create(session_key=session_key)

        # 保存每个答案
        saved_count = 0
        for question_id, answer_value in answers.items():
            try:
                question = Question.objects.get(id=question_id)
                Answer.objects.update_or_create(
                    session=session,
                    question=question,
                    defaults={'value': int(answer_value)}
                )
                saved_count += 1
            except (Question.DoesNotExist, ValueError) as e:
                logger.warning(f"保存答案时跳过题目 {question_id}: {str(e)}")
                continue

        return Response({
            'success': True,
            'message': f'成功保存 {saved_count} 个答案'
        })

    except Exception as e:
        logger.error(f"提交答案时出错: {str(e)}")
        return Response(
            {'error': '服务器内部错误'},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )
# mbti_app/views.py
@api_view(['GET'])
def get_progress(request, session_key):
    """获取答题进度"""
    try:
        session, created = TestSession.objects.get_or_create(session_key=session_key)
        answered_count = Answer.objects.filter(session=session).count()

        # 进度计算基于20道题目
        total_questions = min(Question.objects.count(), MAX_QUESTIONS)
        progress = (answered_count / total_questions) * 100 if total_questions > 0 else 0

        # 确保进度不超过100%
        progress = min(progress, 100)

        return Response({
            'answered': answered_count,
            'total': total_questions,
            'progress': round(progress, 2)
        })

    except Exception as e:
        logger.error(f"获取进度时出错: {str(e)}")
        return Response(
            {'error': '服务器内部错误'},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )

@api_view(['GET'])
def calculate_result(request, session_key):
    """计算MBTI结果"""
    try:
        session = TestSession.objects.get(session_key=session_key)

        # 只获取前20道题目的答案
        all_question_ids = Question.objects.all().order_by('order')[:MAX_QUESTIONS].values_list('id', flat=True)
        answers = Answer.objects.filter(session=session, question_id__in=all_question_ids)

        # 简化的MBTI计算逻辑
        # 实际实现需要根据题目分类和评分规则
        dimensions = {'E': 0, 'I': 0, 'S': 0, 'N': 0, 'T': 0, 'F': 0, 'J': 0, 'P': 0}

        # 这里需要根据实际的题目分类来计算各个维度的得分
        # 暂时返回一个示例结果
        mbti_result = "INTJ"  # 示例结果

        # 保存结果
        session.mbti_result = mbti_result
        session.completed = True
        session.save()

        return Response({'mbti_result': mbti_result})

    except TestSession.DoesNotExist:
        return Response(
            {'error': '会话不存在'},
            status=status.HTTP_404_NOT_FOUND
        )
    except Exception as e:
        logger.error(f"计算结果时出错: {str(e)}")
        return Response(
            {'error': '服务器内部错误'},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )